const dispatch = require('./lib/dispatch')
const K = require('./lib/model/K')
const dao = require('./lib/model/dao')
const reg = require('./lib/register/index')(dao, K)
const repl = require('./lib/repl')
const PORT = 8088

let io = require('socket.io')();
io.on('connection', async function (socket) {
  await dispatch({ io, socket, reg })
  socket.on('disconnect', async function () {
    await reg.disconn(socket)
  })
})

io.listen(PORT)


console.log(`Listening to port ${PORT}`);

//so the program will not close instantly
process.stdin.resume()

async function exitHandler(ev, err) {
  if (err) {
    console.log(err.stack)
  } else {
    process.exit()
  }
}

;['exit', 'SIGINT', 'SIGUSR1', 'SIGUSR2', 'uncaughtException'].forEach(x => {
  process.on(x, exitHandler.bind(null, x))
})

repl('message', {io, reg})